var table;

$(function () {
    // loadQuestionList();
    loadTable();
});

/**
 * 加载问题列表
 */
function loadQuestionList() {
    var url = baseQuestionUrl + "list?start=0&limit=1000000";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        type: "GET",
        headers: {
            "authorization": 'Bearer ' + localStorage.token
        },
        contentType: "application/json",
        success: function (data) {
            loadTable(data.data.rows);
        },
        error: function (request, errorInfo) {
            alert(errorInfo);
        }
    }));
}

function loadTable() {
    table = $("#questionList").DataTable({
        ajax: {
            url: baseQuestionUrl + "list",
            type: "GET",
            contentType: "application/json",
            data: function (req) {
                req.limit = req.length;
                req.search = req.search.value;
            },
            dataSrc: function (res) {
                if(res.code===200&&res.data) {
                    res.recordsTotal = res.data.total;
                    res.recordsFiltered = res.data.total;
                    return res.data.rows;
                }
            },
            error: function (request, error) {
                if (request.status === 401) {
                    $(location).attr('href', 'login.html');
                } else {
                    swal("失败");
                    $('#deleteModal').modal('hide');
                }
            }
        },
        serverSide: true,
        bLengthChange: false,
        ordering: false,
        select: true,
        columns: [
            {data: 'keyWords'},
            {data: 'question'},
            {data: 'guideKeyWords'},
            {
                data: 'actived',
                render: function (data, type, row, meta) {
                    if (data === 1) {
                        return '启用';
                    } else {
                        return '禁用';
                    }
                }
            }
        ],
        pagingType: "full_numbers",
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            oAria: {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        columnDefs: [{
            targets: 4,
            render: function (data, type, row, meta) {
                var string;
                if (row.actived === 1) {
                    string = "禁用";
                } else {
                    string = "启用";
                }
                return "<button type='button' style='margin-right: 10px;border: 1px solid #0D1113;color: #0D1113;background: transparent;' class='btn btn-primary' onclick='editQuestion(" + JSON.stringify(row) + ");'>编辑</button><button type='button' class='btn btn-danger' style='margin-right: 10px;border: 1px solid red;color: red;background: transparent;' onclick='deleteQuestion(" + JSON.stringify(row) + ");'>删除</button><button type='button' class='btn btn-danger' style='border: 1px solid red;color: red;background: transparent;' onclick='disableQuestion(" + JSON.stringify(row) + ");'>" + string + "</button>";
            }
        }]
    });
}

/**
 * 编辑按钮点击事件
 * @param question
 */
function editQuestion(question) {
    if(question) {
        sessionStorage.setItem('questionId', question.id);
    }else{
        sessionStorage.removeItem('questionId')
    }
    initPage('question_list', 'question/question_edit.html');
}

/**
 * 删除按钮点击事件
 * @param question
 */
function deleteQuestion(question) {
    $("#id").text(question.id);
    // $('#deleteModal').modal('toggle');
    swal({
        title: "删除问题",
        text: "确认要删除该问题吗？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#337ab7",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        closeOnCancel: true
    },function(isConfirm) {
        if (isConfirm) {
            var url = baseQuestionUrl + "delete/" + question.id;
            ajaxCommon.request('delete',url,{},function (res) {
                console.log(res);
                if(res.code===200) {
                    swal("删除！", "当前记录已被删除！", "success");
                    table.ajax.reload();
                }
                // $('#deleteModal').modal('hide');
            })
        }
    })

}

/**
 * 禁用按钮点击事件
 * @param question
 */
function disableQuestion(question) {
    var url = baseQuestionUrl + "disable/" + question.id;
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        type: "POST",
        contentType: "application/json",
        success: function (data) {
            if (data.data) {
                if (question.actived === 1) {
                    swal("已禁用");
                } else {
                    swal("已启用");
                }
                // loadTable();
                table.ajax.reload();
            } else {
                swal("失败");
            }
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
                $('#deleteModal').modal('hide');
            }
        }
    }));
}


/**
 * 删除字符串两头的空格
 * @param str
 */
function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
